package com.yixun.qfbao.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.yixun.qfbao.api.service.SendApiService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.dao.ApiLogDao;
import com.yixun.qfbao.model.dto.ApiLogDto;
import com.yixun.qfbao.util.HttpApi;
import com.yixun.qfbao.util.SendResult;
import com.yixun.qfbao.xf.model.dto.SendIntentionListResultDto;
import com.yixun.qfbao.xf.model.dto.SendPremisesResultDto;
import com.yixun.qfbao.xf.model.dto.SendVisitListResultDto;
import com.yixun.qfbao.xf.model.enums.*;
import com.yixun.qfbao.xf.service.CustomerPremisesService;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 恒信 定时推送
 * @author liuqi
 */
@Service
public class SendApiServiceImpl implements SendApiService {

    private static final Logger logger = LoggerFactory.getLogger(SendApiServiceImpl.class);

    private static final String PREMISES_URL = "http://122.4.193.238:5556/putProjectData";
    private static final String VISIT_URL = "http://122.4.193.238:5556/putVisitData";
    private static final String INTENTION_URL = "http://122.4.193.238:5556/putRecordData";

    private static final String SUCCESS = "推送成功";
    private static final String FAIL = "推送失败";

    @Autowired
    private PremisesService premisesService;
    @Autowired
    private CustomerPremisesService customerPremisesService;
    @Autowired
    private ApiLogDao apiLogDao;

    @Override
    public SendPremisesListResDto sendPremisesList(SendReqDto reqDto) {
        SendPremisesListResDto resDto = new SendPremisesListResDto();
        if (null != reqDto.getLastTime() && null != reqDto.getCompanyId()){
            // 查询此次推送的楼盘信息
            List<SendPremisesResultDto> list = premisesService.getSendPremisesList(reqDto.getLastTime(),reqDto.getCompanyId());

             // 判断是否查询到楼盘信息
            if (!CollectionUtils.isEmpty(list)){
                /**
                 * 给楼盘在售状态 赋予枚举值
                 */
                for (SendPremisesResultDto dto : list){
                    dto.setSaleStatus(SaleStatusEnum.getSalesByNo(dto.getSaleStatus()));
                }

                resDto.setPremisesList(list);
                logger.info("定时推送,楼盘信息查询成功:{}",list);

                /**
                 * 推送楼盘信息
                 */
                String requestContent = JSON.toJSONString(list);
                // 调用推送接口
                String responseContent = HttpApi.doPost(PREMISES_URL,requestContent);
                logger.info("定时推送楼盘信息结果：{}",responseContent);
                SendResult sendResult = JSONObject.parseObject(responseContent, SendResult.class);
                if (sendResult.isSucc()){
                    resDto.setResponseMessage(SUCCESS);
                    resDto.setResponseCode(sendResult.getErrno());
                    logger.info("定时推送楼盘信息成功:{}",list);
                }else {
                    resDto.setResponseMessage(FAIL);
                    resDto.setResponseCode(sendResult.getErrno());
                    logger.error("定时推送楼盘信息失败！");
                }

                /**
                 * 存日志
                 */
                saveApiLog(PREMISES_URL
                        ,"楼盘信息"+resDto.getResponseMessage()
                        ,reqDto.getCompanyId()
                        ,JSON.toJSONString(reqDto)
                        ,responseContent
                );
            }else {
                resDto.setResponseMessage("无楼盘信息");
                logger.info("无楼盘信息->{}",reqDto);
            }
        }else {
            resDto.setResponseMessage("lastTime与companyId不能为空");
            logger.error("定时推送楼盘信息,lastTime与companyId为->{}",reqDto);
        }

        return resDto;
    }

    @Override
    public SendVisitListResDto sendVisitList(SendReqDto reqDto) {
        SendVisitListResDto resDto = new SendVisitListResDto();
        if (null != reqDto.getLastTime() && null != reqDto.getCompanyId()){
            // 查询此次推送的到访数据
            List<SendVisitListResultDto> list = customerPremisesService.getSendVisitList(reqDto.getLastTime(),reqDto.getCompanyId());

            // 判断是否查询到到访数据信息
            if (!CollectionUtils.isEmpty(list)){

                resDto.setVisitList(list);
                logger.info("定时推送,到访数据查询成功:{}",list);

                //按每500个一组分割
                List<List<SendVisitListResultDto>> parts = Lists.partition(list, 500);
                parts.stream().forEach(visitList -> {
                    /**
                     * 推送到访数据
                     */
                    String requestContent = JSON.toJSONString(visitList);
                    // 调用推送接口
                    String responseContent = HttpApi.doPost(VISIT_URL,requestContent);
                    logger.info("定时推送到访数据结果：{}",responseContent);
                    SendResult sendResult = JSONObject.parseObject(responseContent, SendResult.class);
                    if (sendResult.isSucc()){
                        resDto.setResponseMessage(SUCCESS);
                        resDto.setResponseCode(sendResult.getErrno());
                        logger.info("定时推送到访数据成功:{}",visitList);
                    }else {
                        resDto.setResponseMessage(FAIL);
                        resDto.setResponseCode(sendResult.getErrno());
                        logger.error("定时推送到访数据失败！");
                    }

                    /**
                     * 存日志
                     */
                    saveApiLog(VISIT_URL
                            ,"到访数据"+resDto.getResponseMessage()
                            ,reqDto.getCompanyId()
                            ,JSON.toJSONString(reqDto)
                            ,responseContent
                    );
                });

            }else {
                resDto.setResponseMessage("无到访数据");
                logger.info("无到访数据->{}",reqDto);
            }
        }else {
            resDto.setResponseMessage("lastTime与companyId不能为空");
            logger.error("定时推送到访数据,lastTime与companyId为->{}",reqDto);
        }

        return resDto;
    }

    @Override
    public SendIntentionListResDto sendIntentionList(SendReqDto reqDto) {
        SendIntentionListResDto resDto = new SendIntentionListResDto();
        if (null != reqDto.getLastTime() && null != reqDto.getCompanyId()){
            // 查询此次推送的报备信息
            List<SendIntentionListResultDto> list = customerPremisesService
                    .getSendIntentionList(reqDto.getLastTime(),reqDto.getCompanyId());

            // 判断是否查询到报备信息
            if (!CollectionUtils.isEmpty(list)){
                /**
                 * 将报备状态，交易状态，报备类型转换成枚举值
                 */
                for (SendIntentionListResultDto dto : list){
                    if (null != dto.getIntentionStatus()){
                        dto.setIntentionStatus(CustomerStatusEnum.getDescByNo(dto.getIntentionStatus()));
                    }
                    if (null != dto.getIntentionType()){
                        dto.setIntentionType(ReportTypeEnum.getDescByNo(dto.getIntentionType()));
                    }
                    if (null != dto.getTradeStatus()){
                        dto.setTradeStatus(ConfirmStatusEnum.getDescByNo(dto.getTradeStatus()));
                    }
                }

                resDto.setIntentionList(list);
                logger.info("定时推送,报备信息查询成功:{}",list);

                //按每500个一组分割
                List<List<SendIntentionListResultDto>> parts = Lists.partition(list, 500);
                parts.stream().forEach(intentionList -> {
                    /**
                     * 推送报备信息
                     */
                    String requestContent = JSON.toJSONString(intentionList);
                    // 调用推送接口
                    String responseContent = HttpApi.doPost(INTENTION_URL,requestContent);
                    logger.info("定时推送报备信息结果：{}",responseContent);
                    SendResult sendResult = JSONObject.parseObject(responseContent, SendResult.class);
                    if (sendResult.isSucc()){
                        resDto.setResponseMessage(SUCCESS);
                        resDto.setResponseCode(sendResult.getErrno());
                        logger.info("定时推送报备信息成功:{}",intentionList);
                    }else {
                        resDto.setResponseMessage(FAIL);
                        resDto.setResponseCode(sendResult.getErrno());
                        logger.error("定时推送报备信息失败！");
                    }

                    /**
                     * 存日志
                     */
                    saveApiLog(INTENTION_URL
                            ,"报备信息"+resDto.getResponseMessage()
                            ,reqDto.getCompanyId()
                            ,JSON.toJSONString(reqDto)
                            ,responseContent
                    );
                });
            }else {
                resDto.setResponseMessage("无报备信息");
                logger.info("无报备信息->{}",reqDto);
            }
        }else {
            resDto.setResponseMessage("lastTime与companyId不能为空");
            logger.error("定时推送报备,lastTime与companyId为->{}",reqDto);
        }
        return resDto;
    }

    /**
     * 存日志
     */
    void saveApiLog(String url, String remark, Long companyId, String request, String response){
        ApiLogDto apiLogDto = new ApiLogDto();
        apiLogDto.setUrl(url);
        apiLogDto.setContent(request);
        apiLogDto.setRemark("定时推送："+remark);
        apiLogDto.setCompanyId(companyId);
        apiLogDto.setCreateTime(Calendar.getInstance().getTime());
        apiLogDto.setRequestContent(request);
        apiLogDto.setResponseContent(response);
        apiLogDao.saveOrUpdate(apiLogDto);
        logger.info("定时推送 -> tm_api_log 日志存储成功");
    }

}
